package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.entity.DTO.SysDepartDTO;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自定义部门管理
 *
 * @Author: zyx
 */
@Api(tags = "自定义部门管理")
@RestController
@RequestMapping("/custom/depart")
@Slf4j
public class CustomDepartController {

    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    public RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysUserDepartService userDepartService;
    @Autowired
    private ISysDepartRoleService departRoleService;
    @Autowired
    private ISysDepartPermissionService departPermissionService;
    @Autowired
    private ISysDepartRolePermissionService departRolePermissionService;
    @Autowired
    private ICustomDeptUnifiedPermissionService deptUnifiedPermissionService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysRolePermissionService rolePermissionService;
    @Autowired
    private ISysDepartRoleUserService departRoleUserService;


    @AutoLog(value = "系统部门角色权限添加")
    @ApiOperation(value = "系统部门角色权限添加", notes = "系统部门角色权限添加")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("deptSystemRolePermissionAdd")
    public Result<?> deptSystemRolePermissionAdd(@RequestParam(name = "ids") String ids,@RequestParam(name = "roleName", required = false) String roleName) {
        String[] splitId = ids.split(",");
        LambdaQueryWrapper<SysDepartRole> wrapper = Wrappers.lambdaQuery(SysDepartRole.class).eq(SysDepartRole::getSystemFlag, 1);
        if (!StringUtils.isEmpty(roleName)) {
            wrapper.eq(SysDepartRole::getRoleName,roleName);
        }
        List<SysDepartRole> projectFileList = departRoleService.list(wrapper);
        for (SysDepartRole departRole : projectFileList) {
            List<SysDepartRolePermission> departRolePermissionList = new ArrayList<>();
            for (String id : splitId) {
                departRolePermissionList.add(new SysDepartRolePermission(departRole.getId(), id));
            }
            departRolePermissionService.saveBatch(departRolePermissionList);
        }
        return Result.OK().success("添加成功");
    }



    @AutoLog(value = "系统部门角色权限删除")
    @ApiOperation(value = "系统部门角色权限删除", notes = "系统部门角色权限删除")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("deptSystemRolePermissionDel")
    public Result<?> deptSystemRolePermissionDel(@RequestParam(name = "ids") String ids,@RequestParam(name = "roleName", required = false) String roleName) {
        String[] splitId = ids.split(",");
        LambdaQueryWrapper<SysDepartRole> wrapper = Wrappers.lambdaQuery(SysDepartRole.class).eq(SysDepartRole::getSystemFlag, 1);
        if (!StringUtils.isEmpty(roleName)) {
            wrapper.eq(SysDepartRole::getRoleName,roleName);
        }
        List<SysDepartRole> projectFileList = departRoleService.list(wrapper);
        for (SysDepartRole departRole : projectFileList) {
            departRolePermissionService.remove(Wrappers.lambdaQuery(SysDepartRolePermission.class).eq(SysDepartRolePermission::getRoleId,departRole.getId()).in(SysDepartRolePermission::getPermissionId,splitId));
        }
        return Result.OK().success("删除成功");
    }

    @AutoLog(value = "一键添加角色")
    @ApiOperation(value = "一键添加角色", notes = "一键添加角色")
    @RequestMapping(value = "/autoAddRole", method = RequestMethod.GET)
    public Result<?> autoAddRole(@RequestParam(name = "deptId") String deptId,@RequestParam(name = "roleName") String roleName,@RequestParam(name = "type") int type) {
        SysDepartRole departRole;
        SysRole sysRole;
        List<SysRolePermission> rolePermissionList;
        List<String> roleIds;

        // 示例
        /*departRole = new SysDepartRole(deptId, "审查受理人员", 1, oConvertUtils.randomGen(16));
        //============设计审查受理人员
        departRoleService.save(departRole);
        //============角色添加权限start
        sysRole = roleService.getOne(Wrappers.lambdaQuery(SysRole.class).eq(SysRole::getRoleCode,"sc_sl"));
        rolePermissionList = rolePermissionService.list(Wrappers.lambdaQuery(SysRolePermission.class).eq(SysRolePermission::getRoleId,sysRole.getId()));
        roleIds = rolePermissionList.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());
        if (oConvertUtils.isNotEmpty(departRole.getId())) {
            departRolePermissionService.saveDeptRolePermission(departRole.getId(), org.apache.commons.lang.StringUtils.join(roleIds, ","), "");
        }*/
        return Result.OK("添加角色成功！","");
    }

    /**
     * 查询数据 查出我的部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
    public Result<List<SysDepartTreeModel>> queryMyDeptTreeList() {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            if (oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
                List<SysDepartTreeModel> list = sysDepartService.queryMyDeptTreeList(user.getDepartIds());
                result.setResult(list);
                result.setMessage(CommonConstant.USER_IDENTITY_2.toString());
                result.setSuccess(true);
            } else {
                result.setMessage(CommonConstant.USER_IDENTITY_1.toString());
                result.setSuccess(true);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<List<SysDepartTreeModel>> queryTreeList() {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        try {
            // 从内存中读取
//			List<SysDepartTreeModel> list =FindsDepartsChildrenUtil.getSysDepartTreeList();
//			if (CollectionUtils.isEmpty(list)) {
//				list = sysDepartService.queryTreeList();
//			}
            List<SysDepartTreeModel> list = sysDepartService.queryTreeList();
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 异步查询部门list
     *
     * @return
     */
    @RequestMapping(value = "/queryDepartTreeSync", method = RequestMethod.GET)
    public Result<List<SysDepartTreeModel>> queryDepartTreeSync(@RequestParam(name = "pid", required = false) String parentId) {
        Result<List<SysDepartTreeModel>> result = new Result<>();
        try {
            List<SysDepartTreeModel> list = sysDepartService.queryTreeListByPid(parentId, null);
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        Result<SysDepart> result = new Result<SysDepart>();
        String username = JwtUtil.getUserNameByToken(request);
        try {
            sysDepart.setCreateBy(username);
            sysDepartService.saveDepartData(sysDepart, username);
            //清除部门树内存
            // FindsDepartsChildrenUtil.clearSysDepartTreeList();
            // FindsDepartsChildrenUtil.clearDepartIdModel();
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 添加公司
     *
     * @param departDTO
     * @return
     */
    @RequestMapping(value = "/addCorp", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE, CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> addZjj(@RequestBody SysDepartDTO departDTO, HttpServletRequest request) {
        if (StringUtils.isEmpty(departDTO.getUsername())) {
            return Result.error("请输入用户名！");
        }
        if (StringUtils.isEmpty(departDTO.getPassword())) {
            return Result.error("请输入密码！");
        }

        String username = JwtUtil.getUserNameByToken(request);
        try {
            departDTO.setCreateBy(username);
            // 部门管理员添加部门需要进行伪关联
            if (!departDTO.getIsAdmin()) {
                LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                departDTO.setRelationParentId(loginUser.getCorpId());
            }
            sysDepartService.saveDepartData(departDTO, username);

            // 非超级管理员需要把添加的部门添加到负责部门
            if (!departDTO.getIsAdmin()) {
                LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                SysUser user = sysUserService.getById(loginUser.getId());
                if (StringUtils.isEmpty(user.getDepartIds())) {
                    user.setDepartIds(departDTO.getId());
                } else {
                    user.setDepartIds(user.getDepartIds() + "," + departDTO.getId());
                }
                sysUserService.updateById(user);
            }
            // 添加用户
            try {
                SysUser user = new SysUser();
                user.setCreateTime(new Date());
                String salt = oConvertUtils.randomGen(8);
                String passwordEncode = PasswordUtil.encrypt(departDTO.getUsername(), departDTO.getPassword(), salt);
                user.setSalt(salt);
                user.setUsername(departDTO.getUsername());
                user.setRealname(departDTO.getUsername());
                user.setPassword(passwordEncode);
                user.setEmail("");
                user.setPhone("");
                user.setStatus(CommonConstant.USER_UNFREEZE);
                user.setDelFlag(CommonConstant.DEL_FLAG_0);
                //此账户默认为上级
                user.setUserIdentity(CommonConstant.USER_IDENTITY_2);
                //账户负责部门
                user.setDepartIds(departDTO.getId());
                user.setActivitiSync(CommonConstant.ACT_SYNC_0);
                user.setCorpId(departDTO.getId());
                //这里需要将用户默认角色设定为 管理员
                if (!departDTO.getIsAdmin()) {
                    // 不是超级管理员添加为 副部门管理员
                    sysUserService.addUserWithRole(user, "1525033870115409921");
                } else {
                    // 超级管理员添加为 总公司管理员
                    sysUserService.addUserWithRole(user, "1525029023209218050");
                }

                //用户绑定部门
                SysUserDepart userDepart = new SysUserDepart(user.getId(), departDTO.getId());
                userDepartService.save(userDepart);
                // 更新部门数据
                departDTO.setUserId(user.getId());
                sysDepartService.updateById(departDTO);
            } catch (Exception e) {
                return Result.error("注册失败");
            }
            //清除部门树内存
            // FindsDepartsChildrenUtil.clearSysDepartTreeList();
            // FindsDepartsChildrenUtil.clearDepartIdModel();
            return Result.OK().success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败！");
        }
    }

    /**
     * 添加单位管理员
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/addAdmin", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE, CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> addAdmin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String deptId = jsonObject.getString("deptId");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        String manageFlag = jsonObject.getString("manageFlag");
        if (StringUtils.isEmpty(username)) {
            return Result.error("请输入用户名！");
        }
        if (StringUtils.isEmpty(password)) {
            return Result.error("请输入密码！");
        }
        if (StringUtils.isEmpty(deptId)) {
            return Result.error("未选择单位！");
        }

        try {
            SysDepart depart = sysDepartService.getById(deptId);
            if (!StringUtils.isEmpty(depart.getUserId())) {
                SysUser zUser = sysUserService.getById(depart.getUserId());
//                return Result.error("此单位已存在管理员，不可添加！");
                // 添加用户
                try {
                    SysUser user = new SysUser();
                    user.setCreateTime(new Date());
                    String salt = oConvertUtils.randomGen(8);
                    String passwordEncode = PasswordUtil.encrypt(username, password, salt);
                    user.setSalt(salt);
                    user.setUsername(username);
                    user.setRealname(username);
                    user.setPassword(passwordEncode);
                    user.setEmail("");
                    user.setPhone("");
                    user.setStatus(CommonConstant.USER_UNFREEZE);
                    user.setDelFlag(CommonConstant.DEL_FLAG_0);
                    //此账户默认为上级
                    user.setUserIdentity(CommonConstant.USER_IDENTITY_2);
                    //账户负责部门
                    user.setDepartIds(zUser.getDepartIds());
                    user.setActivitiSync(CommonConstant.ACT_SYNC_0);
                    if (!StringUtils.isEmpty(manageFlag) && manageFlag.equals("1")) {
                        user.setManageFlag(1);
                    } else {
                        user.setManageFlag(0);
                    }
                    user.setCorpId(deptId);

                    //这里需要将用户默认角色设定为 管理员
                    if (!StringUtils.isEmpty(depart.getParentId())) {
                        // 不是超级管理员添加为 副部门管理员
//                        sysUserService.addUserWithRole(user, "");
                    } else {
                        // 超级管理员添加为 公司管理员
//                        sysUserService.addUserWithRole(user, "");
                    }

                    //用户绑定部门
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), deptId);
                    userDepartService.save(userDepart);
                    // 更新部门数据
                    depart.setUserId(user.getId());
                    sysDepartService.updateById(depart);
                } catch (Exception e) {
                    return Result.error("注册失败");
                }
            } else {
                // 添加用户
                try {
                    SysUser user = new SysUser();
                    user.setCreateTime(new Date());
                    String salt = oConvertUtils.randomGen(8);
                    String passwordEncode = PasswordUtil.encrypt(username, password, salt);
                    user.setSalt(salt);
                    user.setUsername(username);
                    user.setRealname(username);
                    user.setPassword(passwordEncode);
                    user.setEmail("");
                    user.setPhone("");
                    user.setStatus(CommonConstant.USER_UNFREEZE);
                    user.setDelFlag(CommonConstant.DEL_FLAG_0);
                    //此账户默认为上级
                    user.setUserIdentity(CommonConstant.USER_IDENTITY_2);
                    //账户负责部门
                    user.setDepartIds(deptId);
                    user.setActivitiSync(CommonConstant.ACT_SYNC_0);
                    user.setCorpId(deptId);
                    if (!StringUtils.isEmpty(manageFlag) && manageFlag.equals("1")) {
                        user.setManageFlag(1);
                    } else {
                        user.setManageFlag(0);
                    }
                    //这里需要将用户默认角色设定为 管理员
                    if (!StringUtils.isEmpty(depart.getParentId())) {
                        // 不是超级管理员添加为 副公司管理员
//                        sysUserService.addUserWithRole(user, "");
                    } else {
                        // 超级管理员添加为 公司管理员
//                        sysUserService.addUserWithRole(user, "");
                    }

                    //用户绑定部门
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), deptId);
                    userDepartService.save(userDepart);
                    // 更新部门数据
                    depart.setUserId(user.getId());
                    sysDepartService.updateById(depart);
                } catch (Exception e) {
                    return Result.error("注册失败");
                }
            }
            return Result.OK().success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败！");
        }
    }

    @AutoLog(value = "重置监督单位密码")
    @ApiOperation(value = "重置监督单位密码", notes = "重置监督单位密码")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.GET)
    public Result<?> resetPassword(@RequestParam(name = "id", required = true) String id) {
        SysDepart sysDepart = sysDepartService.getById(id);
        SysUser sysUser = sysUserService.getById(sysDepart.getUserId());
        if (sysUser == null) {
            return Result.error("未找到监督单位用户！");
        }
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "123456", salt);
        sysUser.setSalt(salt);
        sysUser.setPassword(passwordEncode);
        boolean flag = sysUserService.updateById(sysUser);
        if (flag) {
            return Result.OK("重置密码成功！", null);
        } else {
            return Result.error("重置密码失败！");
        }
    }

    /**
     * 公司添加部门
     *
     * @param sysDepart
     * @return
     */
    @AutoLog(value = "公司添加部门")
    @ApiOperation(value = "公司添加部门", notes = "公司添加部门")
    @RequestMapping(value = "/addBm", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> addBm(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        Result<SysDepart> result = new Result<SysDepart>();
        String username = JwtUtil.getUserNameByToken(request);
        try {
            sysDepart.setRelationParentId(sysDepart.getParentId());
            sysDepart.setCreateBy(username);
            sysDepartService.saveDepartData(sysDepart, username);
            //============部门添加权限start
            List<CustomDeptUnifiedPermission> deptUnifiedPermissions = deptUnifiedPermissionService.list();
            List<SysDepartPermission> list = new ArrayList<SysDepartPermission>();
            for (CustomDeptUnifiedPermission deptUnifiedPermission : deptUnifiedPermissions) {
                if (deptUnifiedPermission != null && !StringUtils.isEmpty(deptUnifiedPermission.getPermissionId())) {
                    SysDepartPermission rolePms = new SysDepartPermission(sysDepart.getId(), deptUnifiedPermission.getPermissionId());
                    list.add(rolePms);
                }
            }
            departPermissionService.saveBatch(list);
            //============部门添加权限end
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
        String username = JwtUtil.getUserNameByToken(request);
        sysDepart.setUpdateBy(username);
        Result<SysDepart> result = new Result<SysDepart>();
        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
        if (sysDepartEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
            // TODO 返回false说明什么？
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                //FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("修改成功!");
            }
        }
        return result;
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delBm", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> delBm(@RequestParam(name = "id", required = true) String id) {

        Result<SysDepart> result = new Result<SysDepart>();
        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            result.error500("未找到对应实体");
        } else {
            List<SysUser> userList = sysUserService.list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getCorpId, id));
            if (userList != null && userList.size() > 0) {
                boolean ok = sysDepartService.delete(id);
                if (ok) {
                    for (SysUser user : userList) {
                        deleteDeptUser(id, user.getId());
                    }
                    result.success("删除成功!");
                }
//                result.error500("部门下存在用户不可删除");
            } else {
                boolean ok = sysDepartService.delete(id);
                if (ok) {
                    departPermissionService.remove(Wrappers.lambdaQuery(SysDepartPermission.class).eq(SysDepartPermission::getDepartId, id));
                    departRoleService.remove(Wrappers.lambdaQuery(SysDepartRole.class).eq(SysDepartRole::getDepartId, id));
                    departRolePermissionService.remove(Wrappers.lambdaQuery(SysDepartRolePermission.class).eq(SysDepartRolePermission::getDepartId, id));
                    result.success("删除成功!");
                }
            }
        }
        return result;
    }


    /**
     * 删除指定机构的用户
     */
    public Result<SysUserDepart> deleteDeptUser(@RequestParam(name = "depId") String depId,
                                                @RequestParam(name = "userId", required = true) String userId
    ) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id", userId);
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id", depId));
                List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                if (roleIds != null && roleIds.size() > 0) {
                    QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                    query.eq("user_id", userId).in("drole_id", roleIds);
                    departRoleUserService.remove(query);
                    departRolePermissionService.remove(Wrappers.lambdaQuery(SysDepartRolePermission.class).eq(SysDepartRolePermission::getDepartId, depId));
                }
                departPermissionService.remove(Wrappers.lambdaQuery(SysDepartPermission.class).eq(SysDepartPermission::getPermissionId,depId));
                departRoleService.removeByIds(roleIds);
                sysUserService.deleteUser(userId);
                result.success("删除成功!");
            } else {
                result.error500("当前选中部门与用户无关联关系!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> delete(@RequestParam(name = "id", required = true) String id) {

        Result<SysDepart> result = new Result<SysDepart>();
        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDepartService.delete(id);
            if (ok) {
                //清除部门树内存
                //FindsDepartsChildrenUtil.clearSysDepartTreeList();
                // FindsDepartsChildrenUtil.clearDepartIdModel();
                result.success("删除成功!");
            }
        }
        return result;
    }


    /**
     * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
     *
     * @param ids
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        Result<SysDepart> result = new Result<SysDepart>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
     *
     * @return
     */
    @RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
    public Result<List<DepartIdModel>> queryIdTree() {
//		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
//		List<DepartIdModel> idList;
//		try {
//			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//			if (idList != null && idList.size() > 0) {
//				result.setResult(idList);
//				result.setSuccess(true);
//			} else {
//				sysDepartService.queryTreeList();
//				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//				result.setResult(idList);
//				result.setSuccess(true);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.setSuccess(false);
//			return result;
//		}
        Result<List<DepartIdModel>> result = new Result<>();
        try {
            List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
            result.setResult(list);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * <p>
     * 部门搜索功能方法,根据关键字模糊搜索相关部门
     * </p>
     *
     * @param keyWord
     * @return
     */
    @RequestMapping(value = "/searchBy", method = RequestMethod.GET)
    public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord, @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
        Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
        //部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String departIds = null;
        if (oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
            departIds = user.getDepartIds();
        }
        List<SysDepartTreeModel> treeList = this.sysDepartService.searchByKeyWord(keyWord, myDeptSearch, departIds);
        if (treeList == null || treeList.size() == 0) {
            result.setSuccess(false);
            result.setMessage("未查询匹配数据！");
            return result;
        }
        result.setResult(treeList);
        return result;
    }


    /**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysDepart sysDepart, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
        //按字典排序
        Collections.sort(pageList, new Comparator<SysDepart>() {
            @Override
            public int compare(SysDepart arg0, SysDepart arg1) {
                return arg0.getOrgCode().compareTo(arg1.getOrgCode());
            }
        });
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<String> errorMessageList = new ArrayList<>();
        List<SysDepart> listSysDeparts = null;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // orgCode编码长度
                int codeLength = YouBianCodeUtil.zhanweiLength;
                listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
                //按长度排序
                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
                    @Override
                    public int compare(SysDepart arg0, SysDepart arg1) {
                        return arg0.getOrgCode().length() - arg1.getOrgCode().length();
                    }
                });

                int num = 0;
                for (SysDepart sysDepart : listSysDeparts) {
                    String orgCode = sysDepart.getOrgCode();
                    if (orgCode.length() > codeLength) {
                        String parentCode = orgCode.substring(0, orgCode.length() - codeLength);
                        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
                        queryWrapper.eq("org_code", parentCode);
                        try {
                            SysDepart parentDept = sysDepartService.getOne(queryWrapper);
                            if (!parentDept.equals(null)) {
                                sysDepart.setParentId(parentDept.getId());
                            } else {
                                sysDepart.setParentId("");
                            }
                        } catch (Exception e) {
                            //没有查找到parentDept
                        }
                    } else {
                        sysDepart.setParentId("");
                    }
                    //update-begin---author:liusq   Date:20210223  for：批量导入部门以后，不能追加下一级部门 #2245------------
                    sysDepart.setOrgType(sysDepart.getOrgCode().length() / codeLength + "");
                    //update-end---author:liusq   Date:20210223  for：批量导入部门以后，不能追加下一级部门 #2245------------
                    sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
                    ImportExcelUtil.importDateSaveOne(sysDepart, ISysDepartService.class, errorMessageList, num, CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE);
                    num++;
                }
                //清空部门缓存
                Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
                Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
                redisTemplate.delete(keys3);
                redisTemplate.delete(keys4);
                return ImportExcelUtil.imporReturnRes(errorMessageList.size(), listSysDeparts.size() - errorMessageList.size(), errorMessageList);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


    /**
     * 查询所有部门信息
     *
     * @return
     */
    @GetMapping("listAll")
    public Result<List<SysDepart>> listAll(@RequestParam(name = "id", required = false) String id) {
        Result<List<SysDepart>> result = new Result<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
        query.orderByAsc(SysDepart::getOrgCode);
        if (oConvertUtils.isNotEmpty(id)) {
            String arr[] = id.split(",");
            query.in(SysDepart::getId, arr);
        }
        List<SysDepart> ls = this.sysDepartService.list(query);
        result.setSuccess(true);
        result.setResult(ls);
        return result;
    }

    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @RequestMapping(value = "/queryTreeByKeyWord", method = RequestMethod.GET)
    public Result<Map<String, Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
        Result<Map<String, Object>> result = new Result<>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            List<SysDepartTreeModel> list = sysDepartService.queryTreeByKeyWord(keyWord);
            //根据keyWord获取用户信息
            LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<SysUser>();
            queryUser.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
            queryUser.and(i -> i.like(SysUser::getUsername, keyWord).or().like(SysUser::getRealname, keyWord));
            List<SysUser> sysUsers = this.sysUserService.list(queryUser);
            map.put("userList", sysUsers);
            map.put("departList", list);
            result.setResult(map);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据部门编码获取部门信息
     *
     * @param orgCode
     * @return
     */
    @GetMapping("/getDepartName")
    public Result<SysDepart> getDepartName(@RequestParam(name = "orgCode") String orgCode) {
        Result<SysDepart> result = new Result<>();
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
        query.eq(SysDepart::getOrgCode, orgCode);
        SysDepart sysDepart = sysDepartService.getOne(query);
        result.setSuccess(true);
        result.setResult(sysDepart);
        return result;
    }

    /**
     * 根据部门id获取用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getUsersByDepartId")
    public Result<List<SysUser>> getUsersByDepartId(@RequestParam(name = "id") String id) {
        Result<List<SysUser>> result = new Result<>();
        List<SysUser> sysUsers = sysUserDepartService.queryUserByDepId(id);
        result.setSuccess(true);
        result.setResult(sysUsers);
        return result;
    }
}
